package com.dayu.gulimall.order.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author dayu
 * @version 1.0
 * @email dayu007@foxmail.com
 * @date 2021/4/24 22:36
 * @description
 */
@Configuration
public class GuliFeignConfig {

    /**
     * 自定义个拦截器，用户feign客户端调用远程请求的时候，将老的请求信息同步到自己的请求中
     *
     * @return
     */
    @Bean
    public RequestInterceptor requestInterceptor() {
        return requestTemplate -> {
            ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            // 老的请求信息
            HttpServletRequest request = requestAttributes.getRequest();
            if (request != null) {
                String cookie = request.getHeader("Cookie");
                requestTemplate.header("Cookie", cookie);
            }
        };
    }
}
